package org.bitejiuyeke;

import org.bitejiuyeke.utils.DBUtil;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @Author 比特就业课
 */

public class Demo04_Insert {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        // 增，删，改操作不返回结果集，只返回受影响的行数

        try {
            // 1. 获取数据库连接
            connection = DBUtil.getConnection();
            // 2. 定义SQL
            String sql = "insert into bank_account (name, balance) values (?,?)";
            // 3. 定义SQL预处理对象
            statement = connection.prepareStatement(sql);
            // 4. 接收用户输入
            System.out.println("请输入姓名：");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.next();
            System.out.println("请输入余额：");
            BigDecimal balance = new BigDecimal(scanner.next());
            // 5. 用真实数据替换占位符
            statement.setString(1, name);
            statement.setBigDecimal(2, balance);
            // 6. 执行SQL获取结果
            int row = statement.executeUpdate();
            // 7. 判断结果是否成功
            if (row == 1) {
                System.out.println("插入成功");
            } else {
                System.out.println("插入失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(null, statement, connection);
        }

    }
}
